﻿Public Class frmGestionPrestamo
    Dim fechade As Date
    Dim utilidades As New Utilidades
    Dim idUsuarioLogueado As Long = 2 'Cuando se desarrolle el modulo de logueo lo levantamos dinamicamente, por ahora lo ponemos por defecto

    Private Sub cmdSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSalir.Click
        Me.Close()
    End Sub

    Private Sub frmGestionSolicitudPrestamo_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Utilidades.confirmarSalirDelFormulario(e)
    End Sub


    Private Sub frmGestionPrestamo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim myAccesoDatos As New AccesoDatos

        'Cargo Combo de Tipo de Documento
        myAccesoDatos.traer_valores_combo(Me.cmbTipoDocumento, Constantes.Tabla_TIPOS_DOCUMENTOS)

        'Ejecuto una Búsqueda sin Filtros para llenar la Grilla
        Me.buscar(armarWhereConsulta)
    End Sub

    Private Sub cmdCobrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCobrar.Click
        Dim filaSeleccionada As DataGridViewRow
        Dim idPrestamo As Long
        For Each filaSeleccionada In gridPrestamos.SelectedRows
            idPrestamo = filaSeleccionada.Cells(0).Value
        Next

        Dim frmCobroCuota As New frmCobroCuota(idPrestamo)
        frmCobroCuota.ShowDialog()
    End Sub

    Private Sub cmdBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBuscar.Click
        Dim where As New String("")
        Me.buscar(armarWhereConsulta)
    End Sub

    Public Sub buscar(ByVal where As String)
        Dim myAccesoDatos As New AccesoDatos
        Dim myConsulta As String

        myConsulta = "SELECT DISTINCT P.ID, CL.ID AS NRO_CLIENTE, TD.DESCRIPCION AS TIPO_DOCUMENTO,  "
        myConsulta = myConsulta & "CL.NRO_DOCUMENTO, (CL.APELLIDO + ', ' + CL.NOMBRE) AS APELLIDO_NOMBRE, "
        myConsulta = myConsulta & "CONVERT(int, floor(S.MONTO)) AS MONTO, S.CANTIDAD_CUOTAS, "
        myConsulta = myConsulta & "P.PAGADO AS ID_ESTADO_PRESTAMO, CL.ID_ESTADO_CLIENTE AS ID_ESTADO_CLIENTE "
        myConsulta = myConsulta & "FROM PRESTAMOS P INNER JOIN SOLICITUDES_PRESTAMOS S ON (P.ID_SOLICITUD = S.ID) "
        myConsulta = myConsulta & "INNER JOIN CLIENTES CL ON (S.ID_CLIENTE = CL.ID) "
        myConsulta = myConsulta & "INNER JOIN TIPOS_DOCUMENTOS TD ON (CL.ID_TIPO_DOCUMENTO = TD.ID) "


        If Not where.Trim = "" Then
            myConsulta = myConsulta + where
        End If

        Me.gridPrestamos.DataSource = myAccesoDatos.ejecutarConsulta(myConsulta)

        Me.habilitarBotonesSegunGrilla()

    End Sub

    Public Function armarWhereConsulta() As String
        Dim where As New String("")

        If cmbTipoDocumento.SelectedIndex > 0 Then
            where = where + " AND CL.ID_TIPO_DOCUMENTO = " + Convert.ToString(cmbTipoDocumento.SelectedValue)
        End If
        If Not (txtNumeroDocumento.Text().Trim() = "") Then
            where = where + " AND CL.NRO_DOCUMENTO = " + txtNumeroDocumento.Text().Trim()
        End If
        If Not (txtNumeroCliente.Text().Trim() = "") Then
            where = where + " AND CL.ID = " + txtNumeroCliente.Text().Trim()
        End If
        If Me.chkJudicial.Checked = True Then
            where = where & " AND CL.ID_ESTADO_CLIENTE = " & Constantes.Estado_Cliente_Clase3
        Else
            where = where & " AND CL.ID_ESTADO_CLIENTE < " & Constantes.Estado_Cliente_Clase3
        End If

        If Not (txtMonto.Text().Trim() = "") Then
            where = where + " AND S.MONTO = " + txtMonto.Text().Trim()
        End If
        If Me.chkPendiente.Checked = True Then
            where = where & " AND P.PAGADO = 'N' "
        Else
            where = where & " AND P.PAGADO = 'S' "
        End If
        If Me.chkVencida.Checked = True Then
            where = where & " AND P.ID IN ( SELECT PR.ID FROM PRESTAMOS PR INNER JOIN CUOTAS C ON (PR.ID = C.ID_PRESTAMO) "
            where = where & " WHERE C.PAGADA = 'N' AND getDate() > C.FECHA_VENCIMIENTO ) "
        End If

        Return where

    End Function


    Public Sub habilitarBotonesSegunGrilla()
        'Dependiendo si la Grilla tiene resultados habilito los botones
        If Me.gridPrestamos.RowCount < 1 Then
            Me.cmdCobrar.Enabled = False
            Me.cmdReport.Enabled = False
        Else
            Dim filaSeleccionada As DataGridViewRow
            Dim idEstadoPrestamo As New String("")
            Dim idEstadoCliente As Long
            For Each filaSeleccionada In gridPrestamos.SelectedRows
                idEstadoPrestamo = filaSeleccionada.Cells(7).Value
                idEstadoCliente = filaSeleccionada.Cells(8).Value
            Next

            'Solo se pueden cobrar prestamos con cuotas pendientes de pago
            If idEstadoPrestamo = "N" Then
                'Solo se pueden otorgar las solicitudes aprobadas
                If idEstadoCliente = Constantes.Estado_Cliente_Clase3 Then
                    Me.cmdCobrar.Enabled = False
                Else
                    Me.cmdCobrar.Enabled = True
                End If
            Else
                Me.cmdCobrar.Enabled = False
            End If

            Me.cmdReport.Enabled = True
        End If
    End Sub

    Private Sub txtNumeroDocumento_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNumeroDocumento.KeyPress
        utilidades.validarKeyPressNumerico(e)
    End Sub

    Private Sub txtNumeroCliente_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtNumeroCliente.KeyPress
        utilidades.validarKeyPressNumerico(e)
    End Sub

    Private Sub txtMonto_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtMonto.KeyPress
        utilidades.validarKeyPressNumerico(e)
    End Sub

    Private Sub gridSolicitudesPrestamos_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridPrestamos.CellDoubleClick
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridPrestamos.CellMouseClick
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CellMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridPrestamos.CellMouseDoubleClick
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridPrestamos.CellMouseDown
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CellMouseLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridPrestamos.CellMouseLeave
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CellMouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles gridPrestamos.CellMouseMove
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.Click
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.CurrentCellChanged
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.DoubleClick
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.LocationChanged
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.LostFocus
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gridPrestamos.MouseDoubleClick
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles gridPrestamos.MouseDown
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_RowLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gridPrestamos.RowLeave
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub gridSolicitudesPrestamos_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridPrestamos.Sorted
        Me.habilitarBotonesSegunGrilla()
    End Sub

    Private Sub cmdReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReport.Click
        Dim report As New rptPrestamos
        Dim ds As New dsPrestamos
        Dim myAccesoDatos As New AccesoDatos
        Dim myConsulta As String

        myConsulta = "SELECT DISTINCT P.ID, CL.ID AS NRO_CLIENTE, TD.DESCRIPCION AS TIPO_DOCUMENTO,  "
        myConsulta = myConsulta & "CL.NRO_DOCUMENTO, (CL.APELLIDO + ', ' + CL.NOMBRE) AS APELLIDO_NOMBRE, "
        myConsulta = myConsulta & "CONVERT(int, floor(S.MONTO)) AS MONTO, S.CANTIDAD_CUOTAS, "
        myConsulta = myConsulta & "P.PAGADO AS ID_ESTADO_PRESTAMO, CL.ID_ESTADO_CLIENTE AS ID_ESTADO_CLIENTE "
        myConsulta = myConsulta & "FROM PRESTAMOS P INNER JOIN SOLICITUDES_PRESTAMOS S ON (P.ID_SOLICITUD = S.ID) "
        myConsulta = myConsulta & "INNER JOIN CLIENTES CL ON (S.ID_CLIENTE = CL.ID) "
        myConsulta = myConsulta & "INNER JOIN TIPOS_DOCUMENTOS TD ON (CL.ID_TIPO_DOCUMENTO = TD.ID) "

        Dim where As New String("")
        where = armarWhereConsulta()

        If Not where.Trim = "" Then
            myConsulta = myConsulta + where
        End If

        myAccesoDatos.ejecutarConsultaInforme(myConsulta, ds.Prestamos)
        report.SetDataSource(ds)

        Dim frmReportPrestamo As New frmReportPrestamo
        frmReportPrestamo.crvPrestamo.ReportSource = report
        frmReportPrestamo.ShowDialog()
    End Sub
End Class